package cz.khfotbal.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DowloadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private static final int BYTES_DOWNLOAD = 10240;

//	private static final String FILE_DESTINATION = "/var/www/khfotbal.cz/public_www/tmp/";
//	private static final String FILE_DESTINATION = "D://Data//khfotbal//";

	private static String FILE_DESTINATION = "";


	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public DowloadServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String fileName = request.getParameter("id");
		if (fileName == null) {
			response.sendRedirect("/user/index.xhtml");
		}
		System.out.println(fileName);

		FILE_DESTINATION = getServletContext().getRealPath("/");

		File f = new File(FILE_DESTINATION + fileName);
		if (!f.exists()) {
			response.sendRedirect("/user/index.xhtml");
		}
		response.setContentType("application/pdf");
		response.setHeader("Content-Disposition", "attachment; filename="
				+ fileName);
		OutputStream out = response.getOutputStream();
		FileInputStream in = new FileInputStream(FILE_DESTINATION + fileName);
		byte[] buffer = new byte[4096];
		int length;
		while ((length = in.read(buffer)) > 0) {
			out.write(buffer, 0, length);
		}
		in.close();
		out.flush();
		response.flushBuffer();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
